<template>
  <div class="bind-permission">
    <el-row :gutter="24">
      <!-- 左侧角色组列表 -->
      <el-col :span="10">
        <el-card class="role-list" shadow="hover">
          <div slot="header" class="card-header">
            <div class="header-left">
              <i class="el-icon-user-solid"></i>
              <span class="header-title">角色组列表</span>
            </div>
            <el-input v-model="searchRole" placeholder="搜索角色组" prefix-icon="el-icon-search" clearable class="search-input" />
          </div>
          <el-tree :data="roleList" :props="roleProps" :filter-node-method="filterRole" @node-click="handleRoleClick"
            ref="roleTree" node-key="id" class="custom-tree" />
          <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" :total-text="'总数'">
            </el-pagination>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧权限树 -->
      <el-col :span="14">
        <el-card class="permission-tree" shadow="hover">
          <div slot="header" class="card-header">
            <div class="header-left">
              <i class="el-icon-lock"></i>
              <span class="header-title">权限配置</span>
            </div>
            <el-button type="primary" size="small" class="add-btn" @click="savePermissions"
              :disabled="!currentRole">
              <i class="el-icon-plus"></i> 添加权限
            </el-button>
          </div>
          <div v-if="currentRole" class="permission-content">
            <div class="current-role">
              <i class="el-icon-user"></i>
              <span>当前角色：{{ currentRole.roleGroupName }}</span>
            </div>

            <el-table :data="permissionList" style="width: 100%" class="permission-table" stripe :max-height="tableMaxHeight">
              <el-table-column type="index" label="序号" width="80" align="center" />
              <el-table-column prop="permission.path" label="权限" min-width="200" />
              <el-table-column prop="permissionId" label="权限ID" width="120" align="center" />
              <el-table-column prop="permission.method" label="权限标识" width="120" align="center" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="handleDelete(scope.row)" class="delete-btn">
                    <i class="el-icon-delete"></i> 移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-role-selected">
            <i class="el-icon-info"></i>
            <span>请选择左侧角色组</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="添加权限" v-model="dialogVisible" width="50%" class="permission-dialog" :close-on-click-modal="false">
      <el-form-item label="权限" class="permission-select">
        <el-select v-model="selectedPermissions" placeholder="请选择权限" style="width: 100%" filterable multiple
          collapse-tags collapse-tags-tooltip>
          <el-option v-for="item in checkedPermissions" :key="item.permissionId" :label="item.path"
            :value="item.permissionId">
            <span class="permission-id">{{ item.permissionId }}</span>
            <span class="permission-path">{{ item.path }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddPermissions">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BindPermission',
  data() {
    return {
      searchRole: '',
      roleList: [],
      permissionList: [],
      currentRole: null,
      tableMaxHeight: 'calc(100vh - 320px)',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      roleProps: {
        label: 'roleGroupName',
        children: 'children'
      },
      checkedPermissions: [],
      dialogVisible: false,
      selectedPermissions: [],
    }
  },
  watch: {
    searchRole(val) {
      this.$refs.roleTree.filter(val)
    }
  },
  created() {
    this.fetchRoleList()
  },
  methods: {
    // 获取角色组列表
    async fetchRoleList() {
      try {
        let selectedRoleGroup = {
          roleGroupName: this.searchRole
        }
        const response = await this.$post('/findByRoleGroup', {
          data: selectedRoleGroup,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        })
        if (response.code === 200) {
          this.roleList = response.data
          this.pagination.total = response.total
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 获取权限列表

    // 角色搜索过滤
    filterRole(value, data) {
      if (!value) return true
      return data.roleGroupName.toLowerCase().includes(value.toLowerCase())
    },
    // 处理角色点击
    async handleRoleClick(role) {
      this.currentRole = role
      this.$get('/findRoleGroupPermission', {
        roleGroupId: role.roleGroupId,
        path: ''
      }).then(res => {
        if (res.code === 200) {
          this.permissionList = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error('获取角色权限失败')
      })
    },
    // 处理页码改变
    handleCurrentChange(page) {
      this.pagination.currentPage = page
      this.fetchRoleList()
    },
    // 处理每页条数改变
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.currentPage = 1
      this.fetchRoleList()
    },
    findPermissionByNotIn() {
      this.checkedPermissions = []
      this.$get('/findPermissionByNotIn', {
        roleGroupId: this.currentRole.roleGroupId,
      }).then(res => {
        if (res.code === 200) {
          this.checkedPermissions = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error('获取权限失败')
      })
    },
    savePermissions() {
      this.findPermissionByNotIn()
      this.selectedPermissions = [];
      this.dialogVisible = true;
    },
    confirmAddPermissions() {
      if (this.currentRole == null || this.currentRole.roleGroupId == null || this.currentRole.roleGroupId == '') {

        this.$message.warning('请选择要添加权限的角色组');
        return;
      }
      if (!this.selectedPermissions.length) {
        this.$message.warning('请选择要添加的权限');
        return;
      }

      const data = {
        roleGroupId: this.currentRole.roleGroupId,
        permissionIdList: this.selectedPermissions
      }
      this.$post('/saveBatchPermission', data).then(res => {
        if (res.code == 200) {
          this.$message.success('添加成功');
          this.permissionList = []
          this.$get('/findRoleGroupPermission', {
            roleGroupId: this.currentRole.roleGroupId,
            path: ''
          }).then(res => {
            if (res.code === 200) {
              this.permissionList = res.data
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error('获取角色权限失败')
          })
          this.dialogVisible = false;
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        console.log(err);

      })

    },
    //移除权限
    handleDelete(row) {
      this.$msgbox.confirm(
        '确定要移除该权限吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$get('/deleteRoleGroupPermission', {
          id: row.id
        }).then(res => {
          this.$message.success(res.msg)
          this.permissionList = []
          this.$get('/findRoleGroupPermission', {
            roleGroupId: this.currentRole.roleGroupId,
            path: ''
          }).then(res => {
            if (res.code === 200) {
              this.permissionList = res.data
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error('获取角色权限失败')
          })
        }).catch(err => {
          console.log(err);
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.bind-permission {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .el-row {
    margin-bottom: 0;
  }

  .el-card {
    border-radius: 12px;
    border: none;
    transition: all 0.3s ease;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;

      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;

        i {
          font-size: 18px;
          color: #409eff;
        }
      }

      .header-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .search-input {
        width: 200px;
      }
    }
  }

  .role-list {
    height: calc(100vh - 140px);
    display: flex;
    flex-direction: column;

    .custom-tree {
      flex: 1;
      overflow-y: auto;
      padding: 10px 0;

      :deep(.el-tree-node__content) {
        height: 40px;
        border-radius: 6px;
        margin: 2px 0;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        &.is-current {
          background-color: #ecf5ff;
          color: #409eff;
        }
      }
    }

    .pagination-container {
      padding: 16px;
      background-color: #f5f7fa;
      border-top: 1px solid #ebeef5;
      margin-top: auto;
      border-radius: 0 0 12px 12px;
    }
  }

  .permission-tree {
    height: calc(100vh - 140px);

    .permission-content {
      padding: 20px;

      .current-role {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        padding: 12px 16px;
        background-color: #f5f7fa;
        border-radius: 8px;
        color: #606266;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

        i {
          margin-right: 8px;
          font-size: 16px;
          color: #409eff;
        }
      }

      .permission-table {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

        :deep(.el-table__header) {
          th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 600;
            padding: 12px 0;
          }
        }

        :deep(.el-table__row) {
          transition: all 0.3s;

          &:hover {
            background-color: #f5f7fa;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
          }
        }
      }
    }

    .no-role-selected {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 300px;
      color: #909399;

      i {
        font-size: 48px;
        margin-bottom: 16px;
        color: #c0c4cc;
      }
    }
  }

  .add-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 16px;
    border-radius: 20px;
    transition: all 0.3s;
    background: linear-gradient(45deg, #409eff, #36a3f7);

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .delete-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    border-radius: 16px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

.permission-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .el-dialog__header {
      padding: 20px;
      border-bottom: 1px solid #ebeef5;
      background-color: #f5f7fa;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      padding: 20px;
      border-top: 1px solid #ebeef5;
      background-color: #f5f7fa;
    }
  }

  .permission-select {
    .el-select {
      :deep(.el-input__inner) {
        border-radius: 8px;
        transition: all 0.3s;

        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }
    }
  }

  .permission-id {
    font-weight: 500;
    color: #303133;
  }

  .permission-path {
    float: right;
    color: #909399;
    font-size: 13px;
  }
}
</style>
